<?php
/**
 * User: Drery
 * Date: 2015/12/2
 * Time: 18:39
 */

namespace backend\models;


use yii\db\ActiveRecord;

class Role extends ActiveRecord
{
    const ROLE_SUPER = 1;

    public static function tableName()
    {
        return '{{%admin_role}}';
    }

    public function rules()
    {
        return [
            [['title'],'required'],
            ['permissions','default','value'=>[]]
        ];
    }

    public function attributeLabels()
    {
        return [
            'title' => '角色名'
        ];
    }

    public function setPermissions($permissions)
    {
        $this->permissions = $permissions;
    }

    public function getPermissions()
    {
        return $this->hasMany(RolePermission::className(),['admin_role_id'=>'id'])->select('admin_permission_id')->column();
    }

    public function accredit()
    {
        $transaction = $this->getDb()->beginTransaction();
        $originals = $this->getPermissions();
        $news = $this->permissions;
        empty($originals) && $originals = [];
        empty($news) && $news = [];
        $adds = array_diff($news,$originals);
        if (!empty($adds)) {
            foreach ($adds as $admin_permission_id) {
                $model = new RolePermission();
                $model->admin_role_id = $this->id;
                $model->admin_permission_id = $admin_permission_id;
                $model->save();
            }
        }
        $deletes = array_diff($originals,$news);
        !empty($deletes) && RolePermission::deleteAll(['admin_role_id'=>$this->id,'admin_permission_id'=>$deletes]);
        $transaction->commit();
        return true;
    }
}